package com.lzy.webapi.component;

import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.tools.kv.KvClient;
import com.lzy.member.apis.MemberUserServiceApi;
import com.lzy.product.common.constants.RedisPrefixConstants;
import com.lzy.webapi.constants.CommonConstants;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Description:拦截器 Create by lc Date:Apr 10, 2017 Time:6:49:59 PM
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthInterceptor.class);
    @Resource
    private KvClient kvClient;
    @Resource
    private MemberUserServiceApi memberUserServiceApi;
    /**
     * 随机数 :移动端使用
     */
    public static final String SUBMIT_RANDOM = "submitRandom";
    /**
     * redis标识:防止重复提交随机数
     */
    public static final String VALIDATE_TOKEN_RANDOM = "validate_submit:";
    /**
     * 锁标识:防止重复提交随机数
     */
    public static final String LOCK_TOKEN_RANDOM = "lock_submit:";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            Auth auth = ((HandlerMethod) handler).getMethodAnnotation(Auth.class);
            if (auth == null) {
                return true;
            }
            Long userId = isNormal(request.getHeader("token"));
            String random = null;
            // 防止重复提交
            if (auth.validateRepeatSubmit()) {
                random = request.getHeader(SUBMIT_RANDOM);
                return validateRepeatSubmit(userId, random);
            }
            // 生成随机数
            if (auth.generateRandom()) {
                random = RandomStringUtils.random(4, false, true);
                kvClient.save(VALIDATE_TOKEN_RANDOM + userId + random, random, Integer.MAX_VALUE);
                response.setHeader(SUBMIT_RANDOM, random);
                return true;
            }

            return super.preHandle(request, response, handler);

        } else
            return true;

    }

    /**
     * 判断token是否可用/登录信息
     *
     * @返回
     */
    private Long isNormal(String token) {
      Ensure.that(StringUtils.isBlank(token)).isFalse(("00001024"));
        UserToken ut = kvClient.read(RedisPrefixConstants.TOKEN_KEY + token, UserToken.class);
        Ensure.that(ut).isNotNull("00001033");
         /*您的账号，在另一台移动端登录了*/
        if (CommonConstants.TokenStatus.TOKEN_T.equals(ut.getIsClose())) {
            kvClient.delete(RedisPrefixConstants.TOKEN_KEY + token);
            Ensure.that(true).isFalse("00001025");
        }
        return ut.getUserId();
    }

    /**
     * 防止重复提交
     */
    private Boolean validateRepeatSubmit(Long userId, String random) {

        Ensure.that(StringUtils.isBlank(random)).isFalse("10000000");
        String key = VALIDATE_TOKEN_RANDOM + userId + random;
        String lockKey = LOCK_TOKEN_RANDOM + userId + random;
        try {
            kvClient.setNx(lockKey, "");
        } catch (Exception e) {
            Ensure.that(true).isFalse("10000000");
        }

        String randomRedis = kvClient.read(key, String.class);
        Ensure.that(StringUtils.isBlank(randomRedis)).isFalse("10000000");
        kvClient.delete(key);
        kvClient.delete(lockKey);
         /*不需要添加随机数*/
        return Boolean.TRUE;

    }
}
